<template>
  <div class="connect">
    <el-form :inline="true" ref="search_obj" label-width="100px" :rules="rules" :model="search_obj" class="demo-form-inline">
     <el-form-item prop="userId" :label="$t('Order_module.User')">
       <!-- 用户下拉 -->
       <el-select  v-model="search_obj.userId" :placeholder="$t('Order_module.User') ">
         <el-option v-for="item in userList" :key="item.id" :label="item.userName" :value="item.id">
         </el-option>
       </el-select>
     </el-form-item>
    </el-form>
    <div class="down_div">
      <div class="down_div_left">
        <el-button class="down_xlx" @click="createOrder_down">
          <div style="margin-bottom: 15px;">
            <i style="font-size: 30px;" class="el-icon-download" ></i>
          </div>
          {{$t('public.Template_download')}}.xls
        </el-button>
      </div>
      <div class="down_div_left">


        <el-upload
          class="upload-demo"
          drag
          action=""
          :on-change = "beforeupload"
          :file-list="fileList"
          :show-file-list = "false"
          :auto-upload="false"
          >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            <el-button v-if="upFiles" style="width: 300px;" type="text">{{upFiles.name}}</el-button>
            <span v-else>{{$t('public.Drag_the_file_here_or_click_on_upload')}}</span>
          </div>
          <div class="el-upload__tip" slot="tip">{{$t('public.Only_xls_files_can_be_uploaded')}}</div>
        </el-upload>
        <div class="btn_submit_box">
          <el-button style="width: 300px;" :loading="uploadLoading" @click="upFile(upFiles)" type="primary">{{$t('public.submit_order')}}</el-button>
        </div>
      </div>

    </div>
    <!-- <div>
      <div class="list_box">
        <div class="list_box_title">
          {{$t('Order_module.List_of_failed_order_logs')}}
        </div>
        <el-table :data="file_list" border style="width: 100%;margin-top:2vh;">
           <el-table-column min-width="120px" prop="fleName" :label="$t('Order_module.file_name')" align="center" >
           </el-table-column>
           <el-table-column min-width="120px" prop="user_name" :label="$t('public.operator')" align="center" >
           </el-table-column>
           <el-table-column min-width="120px" prop="message" :label="$t('Order_module.failure_reason')" align="center" >
           </el-table-column>
         </el-table>
         <div class="page_box">
           <div>
             <el-pagination
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   :current-page="currentPage"
                   :page-sizes="[10, 50, 100, 200]"
                   :page-size="limit"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="total">
                 </el-pagination>
           </div>

         </div>

      </div>
    </div> -->
  </div>
</template>

<script>
  import store from '@/store'
  import {
    order_searchUser,
  } from '@/api/wqzApi'
  import { getToken } from '@/utils/auth'
  import axios from 'axios'
  export default {
    data() {
      return {
        uploadLoading:false,
        total:0,
        limit:10,
        currentPage:1,
        userList:[],
        rules: { //表单验证
            userId: [{ required: true, message:this.$t('public.Please_select')+ this.$t('Order_module.User'), trigger: 'blur' }],
        },
        search_obj:{
          userId:null , //所选用户
        },
        file_list:[],//失败列标
        upFiles:null ,//上传的文件
        fileList:[

        ]
      }
    },

    created() {
    },
    mounted() {
      this.getUserList()
    },
    destroyed() {

    },
    methods: {
      getUserList(){
        // 筛选条件的userlist
        order_searchUser({}).then(res=>{
          this.userList = res.users
        })
      },
      createOrder_down() {
        console.log(123)
        // POST /api/templatesDown/createOrder
        // 订单批量导入模板下载
        var url = process.env.VUE_APP_BASE_API + '/api/templatesDown/createOrder'
        var  token = getToken()
        axios({
            url: url,
            method: 'post',
            responseType: 'blob',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'Token' : token,
              'Lang' : store.getters.language=="zh"?'zh_CN':'ko_KR'

            }// 重点在于配置responseType: 'blob'
        }).then(res => {
          const name = res.headers['content-disposition'];
                  let fileName = '';
                  if (name) {
                    const str1 = name.replace(' ', '');
                    const arr1 = str1.split(';');
                    arr1.some(item => {
                      if (item.indexOf('filename') != -1) {
                        // fileName = item.split('=')[1];
                        fileName = this.$t('public.Type_a_single_stencil')+'.xlsx'
                      }
                      return item.indexOf('filename') != -1;
                    });
                    if (fileName === ''){
                      fileName = this.$t('public.Type_a_single_stencil')+'.xlsx'
                    }
                  } else {
                    fileName = this.$t('public.Type_a_single_stencil')+'.xlsx'
                  }
            const link = document.createElement('a');  // 创建元素
            let blob = new Blob([res.data]);
            link.style.display = 'none';
            link.href = URL.createObjectURL(blob);   // 创建下载的链接
            link.setAttribute('download', decodeURI(decodeURI(fileName)));  // 给下载后的文件命名
            document.body.appendChild(link);
            link.click();  // 点击下载
            document.body.removeChild(link);  //  下载完成移除元素
            window.URL.revokeObjectURL(link.href);  // 释放掉blob对象
        }).catch(err=> {
          this.$message({
            type:'error',
            message:'Download failed'
          })
        });
      },

      upFile(files){
        // 创建FormData
        var that = this
        this.uploadLoading = true
        if(!files){
          this.$message({
            type:'warning',
            message:this.$t('public.Please_select_Upload_file')
          })
          this.uploadLoading = false
          return
        }
        this.$refs.search_obj.validate((valid) => {
          if (valid) {
            var formData = new FormData()
            formData.append('ordersFile', files)
            formData.append('customerId', that.search_obj.userId)
            var url = process.env.VUE_APP_BASE_API + '/api/order/batchSave'
            var  token = getToken()
            // 设置请求头信息
            const headers = {
              'Content-Type': 'multipart/form-data',
              'Token' : token,
              'Lang' : store.getters.language=="zh"?'zh_CN':'ko_KR'
            }
            axios.post(url, formData, {
              headers
            }).then(res => {
              this.uploadLoading = false
              if(res.data.code == 0){
                this.$message({
                  type:'success',
                  message:this.$t('public.Operation_successful')
                })
              }else{
                this.$message({
                  type:'error',
                  message:res.data.msg
                })
              }

            })
          } else {
            console.log('error submit!!');
            this.uploadLoading = false
            return false;
          }
        });


      },
      onexceed(){
        this.$message('超出数量限制')
      },
      fileRemove(file , filelist){
      console.log('删除' , filelist)
      },
      handleSizeChange(){},
      handleCurrentChange(){},
      beforeupload(files){
        var file = files.raw
        if(file.type == 'application/vnd.ms-excel' || file.type=='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'){
          this.upFiles = file
        }else{
          this.$message('文件格式不符')
          return false
        }
      }
    }
  }
</script>

<style scoped>
  @import url('Batch_order_placement.css');
</style>
